// pages/mall/goodsList/index.js
const $api = require('../../../../request/api').API;
import Toast from '../../../../miniprogram_npm/@vant/weapp/toast/toast';
import {
  calcuActive,
  clearShopCartStorage,
  exceedMessageTip,
  formatGoodsList,
  getFormListStorage,
  getShopCartStorage,
  isAllowAddCart,
  isDockingEvent,
  timeOut
} from '../../../../utils/hooks';
import { getElement, getElementDs, getElements, getFormatDays } from '../../../../utils/util';
const app = getApp();
const animation = wx.createAnimation({
  duration: 200
});
Page({
  data: {
    classifyList: [],
    orderInfo: {},
    name: '',
    thirdClassifyId: '', //三级分类
    collect: '',
    beeperId: '',
    btnId: '',
    btnType: '',
    classifyIds: '',
    latitude: '',
    longitude: '',
    provinceName: '',
    cityName: '',
    areaName: '',
    pageSize: 1000000, //一页的个数
    pageNo: 1, //第几页
    totalPage: 1, //总页数
    listData: [],
    businessList: [],
    businessId: '',
    businessName: '',
    businessLogo: '',
    businessIntroduce: '',
    startPrice: 0,
    tabIndex: 0,
    startClientX: '', //滑动触屏开始的clientX位置
    startClientY: '', //滑动触屏开始的clientY位置
    startPageX: '', //滑动触屏开始的pageX位置
    startPageY: '', //滑动触屏开始的pageY位置

    menuBtnTop: app.globalData.menuBtnTop,
    menuBtnLeft: app.globalData.menuBtnLeft,
    downLoading: false, //懒加载数据
    upLoading: false, //向上加载数据
    loading: true, //加载数据
    empty: false,
    spec: {
      goodsId: '',
      showSpec: false,
      beeperId: ''
    },
    shopCartPosition: '',
    animation: '',
    addAnimation: '',
    businessClassifyList: [],
    // pageNo: 1,
    // pageSize: 20,
    // totalPage: 1,
    businessClassifyId: '',
    businessVillageIds: '',
    fixedTop: 0, //顶部固定定位搜索的高度
    // fixedTop2: 0,//搜索栏和商户的高度和
    // fixedTop4: 0,//商品列表高度到顶部的距离
    // fixedTop5: 0,//商户标题的底部到顶部的距离
    fixedTop6: 0, //列表到顶部的距离
    fixedTop7: 0,
    fixedTop8: 0,
    sideScrollTop: 0,
    listScrollTop: 0,
    listScroll: false,
    sideScroll: false,
    show: true, //是否显示与隐藏顶部的商户图片
    showDot: false,
    dotClientX: '',
    dotClientY: '',
    pageScroll: false,
    openIntroduce: [],
    activeShow: false,
    activeList: [],
    activeItem: null,
    banners: [],
    moreData: true, //是否超过一百条数据
    bottomType: 0, //是否改商户列表数据到底部了
    showOverlay: false,
    formData: {
      show: false,
      val: null
    },
    dateList: [], // 日期列表
    dateId: '', // 选中的日期
    dateScrollInstance: 0,
    isThereCameraAvailable: false
  },
  onLoad: async function (options) {
    // 清掉备注
    delete app.globalData.recordRemark;
    delete app.globalData.remark;
    let beeperId = app.globalData['btnList.beeperId'];
    let latitude = app.globalData['btnList.latitude'];
    let longitude = app.globalData['btnList.longitude'];
    let provinceName = app.globalData['btnList.provinceName'];
    let cityName = app.globalData['btnList.cityName'];
    let areaName = app.globalData['btnList.areaName'];
    let btnId = app.globalData['btnList.btnId'];
    let btnType = app.globalData['btnList.btnType'];
    let classifyIds = app.globalData['btnList.btnServerClassifyIds'];
    let queryType = app.globalData['btnList.queryType'];
    let eventId = app.globalData['btnList.eventId'];
    let type = app.globalData['btnList.type']; //1代表精选 2代表全部
    let shopCartList = getShopCartStorage();
    if (
      app.globalData.shopBeeperId != beeperId ||
      shopCartList.find(item => item.dockingFlag == 2) ||
      isDockingEvent(eventId)
    ) {
      /**
       * 1.进来的时候如果不是与之前相同的呼叫器就清空之前先清空购物车
       * 2.如果本地存储购物车存在对接产品也清空
       * 3.本身是对接类型也清空
       */
      clearShopCartStorage();
    }

    app.globalData.shopBeeperId = beeperId;
    this.setData({
      'spec.beeperId': beeperId,
      btnId: btnId,
      beeperId: beeperId ? beeperId : '',
      classifyIds: classifyIds,
      btnType: btnType,
      queryType: queryType,
      latitude: latitude ? parseFloat(latitude) : '',
      longitude: longitude ? parseFloat(longitude) : '',
      provinceName: provinceName,
      cityName: cityName,
      areaName: areaName,
      eventId
    });
    if (eventId == 18) {
      // eventId为18表示挂号对接,需要日期
      const dateList = getFormatDays(7);
      this.setData({
        dateList,
        dateId: dateList[0].id
      });
      app.globalData['dock.date'] = dateList[0].date;
    }
    await this.initGetStyle();
    await this.getBusinessList();
    if (this.data.businessId) {
      await this.getActiveList();
      await this.getBannerList();
      await this.getBusinessClassifyList();
    }

    this.getStyle();
    wx.nextTick(() => {
      this.setData({
        pageScroll: true
      });
    });
  },

  onShow: function () {
    // 每一次进来的时候都需要根据本地存储的购物车来修改列表中商品的数量
    let shopCartList = JSON.parse(wx.getStorageSync('shopCartData'));
    this.data.listData.forEach(item => {
      item.nums = 0;
      shopCartList.forEach(item2 => {
        if (item.variantId == item2.variantId) {
          item.nums = item2.nums;
        }
        if (item.goodsId == item2.goodsId && !item.variantId) {
          item.nums = item.nums + item2.nums;
        }
      });
    });
    const { businessId } = app.globalData;
    // 这里如果存在商户id就需要跳到目标商户去
    if (businessId) {
      const e = {};
      e.detail = {
        name: businessId
      };
      this.businessChange(e);
      delete app.globalData.businessId;
    }

    this.setData({
      listData: this.data.listData
    });
  },
  async initGetStyle() {
    const res = await getElement('.top-fixed');
    this.setData({
      fixedTop: res[0].bottom
    });
  },
  getStyle() {
    const { fixedTop } = this.data;
    wx.nextTick(() => {
      getElementDs([
        '.business-wrapper',
        '.collect-wrapper',
        '.business-info',
        '.silder-wrapper',
        '#balance>>>.shop-cart-img'
      ]).then(res => {
        this.setData({
          // fixedTop2: fixedTop + res[0].height, // [顶部搜索、商户]高度和
          fixedTop3: fixedTop + res[0].height + res[1].height, // [顶部搜索、商户的高度、我的收藏]高度和
          // fixedTop4: res[0].top,// 没用了
          // fixedTop5: res[2].bottom,// 商户信息底部到页面顶部的距离
          fixedTop6: res[3].top - (fixedTop + res[0].height + res[1].height),
          shopCartPosition: res[4],
          fixedTop7: res[4].top
        });
      });
      if (this.data.businessIntroduce) {
        getElement('.business-introduce').then(res => {
          this.setData({
            fixedTop8: res[0].bottom
          });
        });
      }
    });
  },
  // 返回上一页
  back() {
    wx.navigateBack({
      delta: 1
    });
  },
  // 阻止冒泡
  stopBubble() {},
  // 输入
  inputChange(e) {
    this.setData({
      name: e.detail
    });
  },
  // 点击搜索产品
  async searchGoods(e) {
    const { name, fixedTop6, classifyIds, businessId, businessList, queryType, beeperId, btnId } = this.data;
    const { collect } = e.currentTarget.dataset;
    const modifyData = {
      pageNo: 1,
      businessClassifyList: []
    };
    collect !== undefined && (modifyData.collect = collect);
    this.setData(modifyData);

    if (collect !== undefined) {
      // 点击的收藏
      await this.getListData();
    } else if (name) {
      // 存在关键字
      const businessVillageIds = businessList.reduce((a, b) => a.concat(b.businessVillageIds || []), []);
      let businessIds = Array.from([businessId, ...businessList.map(item => item.id)]).toString();
      const params = {
        name,
        businessIds
      };
      if (queryType == 1) {
        params.beeperId = beeperId;
        params.btnId = btnId;
      } else {
        params.classifyIds = classifyIds;
        params.businessVillageIds = businessVillageIds.toString();
      }
      const res = await $api.getBusinessByName(params);
      const id = res.data.data;
      this.businessChange({
        detail: {
          name: id || businessId
        }
      });
    } else {
      // 不存在收藏和关键字
      await this.getBusinessClassifyList();
    }
    wx.pageScrollTo({
      scrollTop: fixedTop6,
      duration: 0
    });
  },
  // 显示商户介绍
  showIntroduce(e) {
    wx.pageScrollTo({
      scrollTop: 0,
      success: () => {
        const { openIntroduce } = this.data;
        this.setData({
          openIntroduce: openIntroduce.length ? [] : ['1'],
          pageScroll: openIntroduce.length ? true : false
        });
      }
    });
  },
  // 显示活动介绍
  showActivePopup(e) {
    const { item } = e.currentTarget.dataset;
    this.setData({
      activeShow: true,
      activeItem: item
    });
  },
  closeActivePopup() {
    this.setData({
      activeShow: false
    });
  },
  // 去订单页面
  toOrder() {
    wx.switchTab({
      url: '../../order/index'
    });
  },
  // 获取商户列表
  async getBusinessList() {
    let params = {
      type: 1,
      btnId: this.data.btnId,
      beeperId: this.data.beeperId,
      btnType: this.data.btnType,
      classifyIds: this.data.classifyIds,
      queryType: this.data.queryType,
      latitude: this.data.latitude,
      longitude: this.data.longitude,
      provinceName: this.data.provinceName,
      cityName: this.data.cityName,
      areaName: this.data.areaName
    };
    try {
      let res = await $api.getBusinessList(params);
      let data = res.data.data || [];
      let businessVillageIds = '';
      if (!data.length) {
        Toast('暂无服务');
        setTimeout(() => {
          wx.navigateBack(-1);
        }, 2000);
        return false;
      }
      this.getBusinessCamera(data[0].id);
      let res2 = data.find(item => data[0].id == item.id);
      if (res2.businessVillageIds && res2.businessVillageIds.length > 0) {
        businessVillageIds = res2.businessVillageIds.join(',');
      }
      this.setData({
        businessList: data,
        businessId: data[0].id,
        startPrice: data[0].startPrice,
        businessName: data[0].name,
        businessLogo: data[0].logo,
        businessIntroduce: data[0].introduce,
        businessVillageIds
      });
    } catch (err) {
      if (err && err.status == 601) {
        // 当前商户是会员的，但是当前用户不是会员就报错就
        setTimeout(() => {
          wx.navigateBack();
        }, 2000);
      }
      return Promise.reject();
    }
    if (this.selectComponent('#tabs')) this.selectComponent('#tabs').resize();
  },
  // 获得商户摄像头
  getBusinessCamera(businessId) {
    this.setData({ isThereCameraAvailable: false });
    $api.checkoutBusinessCamera({ businessId }).then(res => {
      this.setData({ isThereCameraAvailable: res.data.data > 0 });
    });
  },

  handleGotoCameraList() {
    wx.navigateTo({
      url: '../listMerchantCameras/index?businessId=' + this.data.businessId
    });
  },
  // 获取商户自定义分类
  async getBusinessClassifyList() {
    const { businessId, btnId, queryType, btnType, classifyIds, beeperId, businessList } = this.data;
    const params = {
      businessId,
      type: 1,
      btnId,
      queryType,
      btnType,
      beeperId,
      classifyIds
    };
    const businessVillageIds = businessList.find(item => item.id == businessId).businessVillageIds.toString();
    const res = await $api.getBusinessClassifyList(params);
    const params2 = Object.assign(params, {
      businessVillageIds,
      serverClassifyIds: params.classifyIds
    });
    const res2 = await $api.countBusinessGoods(params2);
    const list = res.data.data || [];
    list.forEach(item => {
      item.name = item.name.replace(/\<img/gi, '<img style="width:auto;height:17px;vertical-align:-3px"');
    });
    this.setData({
      businessClassifyList: list,
      tabIndex: 0,
      moreData: res2.data.data > 50 ? true : false
    });
    this.getListData();
  },
  // 获取活动
  async getActiveList() {
    let res = await $api.getActiveList({
      businessId: this.data.businessId
    });
    this.setData({
      activeList: res.data.data || []
    });
  },
  // 获取banners
  async getBannerList() {
    let res = await $api.getBannerList({
      businessId: this.data.businessId,
      serverClassifyIds: this.data.classifyIds
    });
    res = res.data.data;
    this.setData({
      banners: res.length
        ? res
        : [
            {
              id: 1,
              value: 'https://pic.kanglailab.com/kics_web/classifyBannerImg/1699879262018173132.jpg'
            },
            {
              id: 2,
              value: 'https://pic.kanglailab.com/kics_web/classifyBannerImg/1699879265858401248.jpg'
            }
          ]
    });
  },
  // 获取商品数据
  async getListData() {
    let shopCartList = JSON.parse(wx.getStorageSync('shopCartData'));
    let res = null;
    let list = [];
    const {
      businessList,
      businessId,
      btnId,
      beeperId,
      btnType,
      classifyIds,
      queryType,
      pageSize,
      pageNo,
      businessClassifyList,
      name,
      tabIndex,
      listData,
      moreData,
      collect,
      dateId
    } = this.data;
    let params = {
      btnId,
      beeperId,
      btnType,
      classifyIds,
      businessId,
      queryType,
      strDate: dateId
    };
    this.waitGetData = true; // 获取数据之前不能再次请求数据
    let item = businessList.find(item => businessId == item.id);
    if (item.businessVillageIds && item.businessVillageIds.length > 0) {
      params.businessVillageIds = item.businessVillageIds.join(',');
    }
    if (listData.length) {
      this.setData({
        downLoading: true
      });
    }
    if (moreData || name || collect) {
      params.pageNo = pageNo;
      params.pageSize = pageSize;
      if (name || collect) {
        params.name = name;
        params.collect = collect;
      } else {
        // 只有不是搜索的时候才会有分类
        params.businessClassifyId = businessClassifyList.length ? businessClassifyList[tabIndex].id || '' : '';
      }
      this.setData({
        loading: true
      });
      res = await $api.getShopList(params);
      res = res.data.data;
      list = res.list || [];
    } else {
      params.businessClassifyIds = businessClassifyList.length
        ? businessClassifyList.map(item => item.id).toString()
        : '';
      res = await $api.getGoodsList(params);
      res = res.data.data;
      list = res || [];
      if (businessClassifyList.length) {
        list = list.flatMap(item => item.list);
      }
    }

    // 添加一个nums属性，同时判断购物车里面是否存在该商品，如果存在那么就需要把该商品的数量赋值给商品列表对应的该商品
    list.forEach((item, index) => {
      item.nums = 0;
      shopCartList.forEach(item2 => {
        if (item.variantId == item2.variantId) {
          item.nums = item2.nums;
        }
        if (item.goodsId == item2.goodsId && !item.variantId) {
          item.nums = item.nums + item2.nums;
        }
      });
    });

    // 存在商户有商户分类就需要添加标题添加标题
    if (!name && !collect) {
      if (moreData) {
        if (pageNo == 1 && businessClassifyList.length && moreData) {
          list[0].businessClassifyName = businessClassifyList[tabIndex].name;
        }
        list = pageNo == 1 ? list : listData.concat(list);
      } else {
        if (businessClassifyList.length) {
          (res || []).forEach(item => {
            item.list[0].businessClassifyName = businessClassifyList.find(
              item2 => item2.id == item.businessClassifyId
            ).name;
          });
        }
      }
    }

    formatGoodsList(list);
    // // 判断是否在活动范围内
    // this.activeTime(list)
    // this.judgeTimeout(list)

    this.setData(
      {
        listData: list,
        pageNo: moreData ? res.pageNum : 1,
        totalPage: moreData ? res.totalPage : 1,
        empty: list.length > 0 ? false : true
      },
      () => {
        this.waitGetData = false;
        this.judgeClassify();
      }
    );
    // 判断是否超时

    // 是否显示请求下一个商户
    this.isNextBusinss();

    if (this.selectComponent('#tabs')) this.selectComponent('#tabs').resize();
    this.setData({
      downLoading: false,
      upLoading: false,
      loading: false
    });
  },
  // 滚动触发
  async goodsListScroll(e) {
    if (this.clickClassify) {
      // 滚动的时候点击分类，就不执行滚动下面的内容
      // this.clickClassify = false
      return;
    }
    this.recordScroll();
    // 滚动与滑动开始里面的scroll合在一起使用用来判断开始是否滚动
    if (this.data.moreData) {
      this.scroll = true;
      return;
    }
    // debounce(async ()=>{
    if (this.scrollTimer) clearTimeout(this.scrollTimer);
    this.scrollTimer = setTimeout(async () => {
      this.judgeClassify();
    }, 30);
    // },1000)()
  },
  // 滚动判断到哪个分类
  async judgeClassify() {
    const res1 = await getElements('.business-classify_name');
    const res2 = await getElements('.sidebar');
    const res3 = await getElement('.list-wrapper');
    const listTop = res3[0].top;
    const { businessClassifyList, fixedTop7, moreData } = this.data;
    if (!businessClassifyList.length) return;
    res1[0].reverse();
    res1[0].find(item => {
      if (item.top <= listTop + 5) {
        let index = businessClassifyList.findIndex(item2 => item2.id == item.id.split('a')[1]);
        if (!this.clickClassify && !moreData) {
          this.setData({
            tabIndex: index
          });
        }
        const top = res2[0][index].top;
        const bottom = res2[0][index].bottom;
        const firstTop = res2[0][0].top;
        const lastTop = res2[0].at(-1).top;
        if (top < listTop) {
          this.setData({
            sideScrollTop: top - firstTop + 10
          });
        } else if (bottom > fixedTop7) {
          let val = lastTop - top + listTop - firstTop;
          if (lastTop == top) {
            val = val + top;
          }
          this.setData({
            sideScrollTop: val
          });
        }
        return true;
      }
    });
  },
  drageEnd() {},
  // 滑动开始
  async drageStart() {
    this.scroll = false;
    const { fixedTop3, tabIndex, moreData } = this.data;
    if (!moreData) return;
    const res = await getElement('.silder-wrapper');
    this.setData({
      pageScroll: res[0].top - 2 <= fixedTop3 && tabIndex ? false : true
    });
  },
  sideDrageStart() {
    this.setData({
      pageScroll: true
    });
  },
  // 列表滚动到底部的时候触发
  scrollToLower() {
    const { pageNo, totalPage, moreData } = this.data;
    if (!moreData || pageNo == totalPage || this.waitGetData) return;
    this.setData({
      pageNo: pageNo + 1
    });
    this.getListData();
  },
  // 商户改变
  async businessChange(e) {
    // 如果e.detail的值是数字那么就是侧边栏搜索的商品
    const { businessList, collect } = this.data;
    const { name } = e.detail;
    const business = businessList.find(item => item.id == name);

    let res = businessList.find(item => name == item.id);
    let businessVillageIds = '';
    if (res.businessVillageIds && res.businessVillageIds.length > 0) {
      businessVillageIds = res.businessVillageIds.join(',');
    }
    this.getBusinessCamera(name);
    this.setData({
      businessId: name,
      startPrice: business.startPrice,
      businessName: business.name,
      businessLogo: business.logo,
      businessIntroduce: business.introduce,
      listScrollTop: true,
      sideScrollTop: true,
      businessVillageIds,
      pageNo: 1,
      showOverlay: true
    });
    await this.getActiveList();
    await this.getBannerList();
    if (this.data.name || collect) {
      await this.getListData(true);
    } else {
      await this.getBusinessClassifyList();
    }

    wx.pageScrollTo({
      scrollTop: 0,
      duration: 0,
      success: async () => {
        // 每次切换商户都需要重新计算列表距离顶部的高度
        const res = await getElement('.silder-wrapper');
        this.setData({
          listScrollTop: 0,
          sideScrollTop: 0,
          listScroll: false,
          sideScroll: false,
          pageScroll: true,
          fixedTop6: res[0].top - this.data.fixedTop3
        });
        setTimeout(() => {
          this.setData({
            showOverlay: false
          });
        }, 300);
      }
    });
  },
  // 商户分类改变
  async businessClassifyChange(e) {
    /**
     * 这里有两个重要的变量
     * clickClassify 如果存在这个函数
     */
    clearTimeout(this.scrollTimer);
    this.clickClassify = true;
    const { item, index } = e.currentTarget.dataset;
    const { moreData } = this.data;
    this.setData({
      tabIndex: index,
      listScroll: false
    });
    wx.pageScrollTo({
      scrollTop: this.data.fixedTop6,
      duration: 0
    });
    wx.nextTick(async () => {
      this.setData({
        listScroll: true
      });
      if (moreData) {
        this.setData({
          pageNo: 1,
          listScrollTop: 0
          // sideScrollTop: 0,
          // listScroll:true
        });
        await this.getListData();
        this.clickClassify = false;
      } else {
        setTimeout(() => {
          this.clickClassify = false;
          this.setData({
            viewId: 'a' + item.id
          });
        }, 70);
      }
    });
    // }
  },
  // 是否显示去下一个商户
  isNextBusinss() {
    const { moreData, businessList, businessId, businessClassifyList, tabIndex, pageNo, totalPage } = this.data;
    const isLastClassify = !businessClassifyList.length || businessClassifyList.length == tabIndex + 1;
    const isLastbusiness = businessList.length && businessList.at(-1).id == businessId;
    let flag = (moreData ? (pageNo == totalPage && isLastClassify ? true : false) : true) && businessList.length > 1;
    this.setData({
      bottomType: flag ? (isLastbusiness ? 2 : 1) : 0
    });
  },
  // 点击去下一或者上一个商户个商户
  async switchBusiness() {
    const { businessId, businessList, bottomType } = this.data;
    let index = businessList.findIndex(item => item.id == businessId);
    bottomType == 1 ? index++ : index--;
    this.businessChange({
      detail: {
        name: businessList[index].id
      }
    });
  },
  // 去商品详情页面
  toGoodsDetail(e) {
    let goodsId = e.currentTarget.dataset.goodsid;
    let beeperBtnId = e.currentTarget.dataset.beeperBtnId;
    wx.navigateTo({
      url: '/subcontract/home/pages/goodsDetail/index?goodsId=' + goodsId + '&beeperBtnId=' + beeperBtnId
    });
  },
  // 添加
  async addNum(e) {
    // 这里有三种情况，触发该函数
    // 1.事件绑定触发
    // 2.balance组件自定义事件触发
    // 3.goods-spec组件触发
    // 如果e.detail.goodsId存在那么就表示是子组件触发的这个函数
    const shopCartList = getShopCartStorage();
    let obj = null;
    let variantId = null;
    let indexArr = [];
    let { listData, beeperId } = this.data;
    const { item } = e.currentTarget.dataset;
    const goods = e.detail.goodsId ? e.detail : item;
    const { goodsId } = goods;
    const eventId = app.globalData['btnList.eventId'];
    if (
      !isAllowAddCart({
        goods,
        eventId,
        shopCartList
      })
    )
      return;
    if (this.timeOut(goodsId)) return;

    if (e.detail.goodsId) {
      // 是goods-spec或者是balance组件调用的
      indexArr = this.getIndexsById(listData, e.detail.goodsId, 'goodsId');

      // const o =
      obj = {
        ...(listData[indexArr[0]] || {}),
        ...e.detail
      };

      e.currentTarget.dataset.item = {};
      e.currentTarget.dataset.item.variantId = e.detail.variantId;
      if (indexArr.length) {
        // 可能有重复的数据
        indexArr.forEach(i => (listData[i].nums = listData[i].nums + e.detail.nums));
        this.setData({
          listData
        });
      }
    } else {
      // 事件绑定触发,这里需要判断有没有关联产品而且至少有没有添加一个
      variantId = item.variantId;
      // 全局添加一个variantId
      app.globalData['btnList.variantId'] = variantId;
      indexArr = this.getIndexsById(listData, variantId, 'variantId');
      // 如果存在关联产品拉起选择关联产品的框框
      if (beeperId && item.relationFlag && !listData[indexArr[0]].nums) {
        let spec = this.data.spec;
        spec.goodsId = item.goodsId;
        (spec.showSpec = true),
          this.setData({
            spec
          });
        return;
      } else {
        if (await this.judgeShowForm(item, e)) return;
        // 正常添加数据
        // 执行添加动画
        this.addAni(e.touches[0]);
        indexArr.forEach(i => listData[i].nums++);
        obj = Object.assign(
          {
            ...listData[indexArr[0]]
          },
          {
            nums: 1
          }
        );
      }
      // 判断是否在活动范围之内
      // const goodsList = this.data.listData.filter(item => item.goodsId == goodsId)
      // if (goodsList.length) {
      //   this.activeTime(goodsList)
      // }
      calcuActive(listData.filter(item => item.goodsId == goodsId));
      this.setData({
        listData
      });
    }

    // 执行父组件的addNum方法也会执行子组件的addNum方法，子组件也会执行父组件的，所以必须要用一个属性来控制，否则会陷入死循环
    if (!e.detail.flag) {
      e.flag = true;
      this.selectComponent('#balance').addNum(e, obj);
    }
  },
  // 购物车改变数量
  async shopCartChangeNum(e) {
    const { listData } = this.data;
    const { goodsId, nums } = e.detail;
    const indexArr = this.getIndexsById(listData, goodsId, 'goodsId');
    if (!indexArr.length) return;
    indexArr.forEach(item => (listData[item].nums = nums));
    this.setData({
      listData
    });
  },
  addCart() {
    this.addNum(this.event);
  },
  // 判断是否需要显示弹框
  async judgeShowForm(goods, e) {
    if (!goods.attrMark) return false;
    const res = await getFormListStorage(goods);
    if (res.isStorage) return; // 如果本地存储存在就不需要
    const { formData } = this.data;
    formData.val = res;
    formData.show = true;
    this.setData({
      formData
    });
    this.event = e;
    return true;
  },
  // 添加动画
  addAni({ clientX, clientY }) {
    const { top, right } = this.data.shopCartPosition;
    this.setData({
      showDot: true,
      dotClientX: clientX - 4,
      dotClientY: clientY - 8
    });
    wx.nextTick(() => {
      const addAnimation = wx
        .createAnimation()
        .top(clientY - 20)
        .left(clientX - 50)
        .step({
          duration: 100
        })
        .top(top)
        .left(right - 12)
        .step({
          duration: 100,
          timingFunction: 'ease-in'
        });
      this.setData({
        addAnimation: addAnimation.export()
      });
      setTimeout(() => {
        this.setData({
          showDot: false,
          addAnimation: null
        });
      }, 250);
    });
  },
  // 减少
  subNum(e) {
    let indexArr = [];
    const goodsId = e.detail.goodsId || e.currentTarget.dataset.item.goodsId;
    if (this.timeOut(goodsId)) return;
    const { listData } = this.data;
    if (e.detail.goodsId) {
      indexArr = this.getIndexsById(listData, e.detail.goodsId, 'goodsId');
      e.currentTarget.dataset.item = {};
      e.currentTarget.dataset.item.variantId = e.detail.variantId;
      if (indexArr.length > 0) {
        indexArr.forEach(i => listData[i].nums--);
        this.setData({
          listData
        });
      }
    } else {
      // index = this.getIndexById(this.data.listData, e.currentTarget.dataset.item.variantId, "variantId")
      indexArr = this.getIndexsById(listData, e.currentTarget.dataset.item.variantId, 'variantId');
      indexArr.forEach(i => listData[i].nums--);

      calcuActive(listData.filter(item => item.goodsId == goodsId));
      // const goodsList =
      // if (goodsList.length) this.activeTime(goodsList)

      this.setData({
        listData
      });
    }

    // {
    //   this.activeTime(goodsList)
    // }
    if (!e.detail.flag) {
      e.flag = true;
      this.selectComponent('#balance').subNum(e);
    }
  },
  // 清空数量
  clear() {
    const { listData } = this.data;
    listData.forEach(item => (item.nums = 0));
    this.setData({
      listData
    });
  },
  // 判断哪些产品不在销售时间内
  // judgeTimeout(listData) {
  //   listData.forEach(item => {
  //     let res = null
  //     if (!item.goodsHours || item.goodsHours && !item.goodsHours.length) {
  //       return
  //     }
  //     res = item.goodsHours.some(item => {
  //       let time = new Date()
  //       let begin = new Date()
  //       let end = new Date()
  //       const arr = item.beginHours.split(":").map(item => Number(item))
  //       const arr2 = item.endHours.split(":").map(item => Number(item))
  //       begin.setHours(arr[0])
  //       begin.setMinutes(arr[1])
  //       end.setHours(arr2[0])
  //       end.setMinutes(arr2[1])
  //       return time.getTime() > begin.getTime() && time.getTime() < end.getTime()
  //     })
  //     if (!res) {
  //       item.saleState = 0
  //       item.nums = 0
  //     }
  //   })
  // },
  // 判断某个产品是否在时间段内，如果不在就要是售罄的
  timeOut(goodsId) {
    const { listData } = this.data;
    if (timeOut(goodsId, listData)) {
      this.setData({
        listData
      });
      this.selectComponent('#balance').timeOut(goodsId);
      return true;
    }
    // const { listData } = this.data
    // let goods = listData.find(item => item.goodsId == goodsId)
    // if (!goods) {
    //   // 如果列表里面没有的话就直接添加
    //   return false
    // }
    // if (!goods.goodsHours || goods.goodsHours && !goods.goodsHours.length) return
    // const res = goods.goodsHours.some(item => {
    //   let time = new Date()
    //   let begin = new Date()
    //   let end = new Date()
    //   const arr = item.beginHours.split(":").map(item => Number(item))
    //   const arr2 = item.endHours.split(":").map(item => Number(item))
    //   begin.setHours(arr[0])
    //   begin.setMinutes(arr[1])
    //   end.setHours(arr2[0])
    //   end.setMinutes(arr2[1])
    //   return time.getTime() > begin.getTime() && time.getTime() < end.getTime()
    // })
    // if (!res) {
    //   // 售罄之后改变状态同时清空购物车里面售罄的该数据
    //   goods.nums = 0
    //   goods.saleState = 0
    //   this.setData({
    //     listData
    //   })
    //   this.selectComponent("#balance").timeOut(goodsId)
    //   return true
    // } else {
    //   return false
    // }
  },
  //需要判断是不是活动时间
  // activeTime(val) {
  //   val = Array.isArray(val) ? val : [val] //拼接一个数组好计算
  //   val.forEach(item => {
  //     if (!item.active) return
  //     let { beginDate, endDate, activePrice } = item.active
  //     beginDate = getDatetime(beginDate).getTime()
  //     endDate = getDatetime(endDate).getTime()
  //     let nowDate = new Date().getTime()
  //     if (nowDate > beginDate && nowDate < endDate) {
  //       item.activeDiscount = parseFloat(((activePrice / item.price) * 10).toFixed(2)) || 10
  //     } else {
  //       item.activeDiscount = ""
  //     }
  //   })
  // },
  // 选择规格
  selectSpec(e) {
    let item = e.currentTarget.dataset.item;
    if (item.specDisplayType == 1) {
      // 跳转到规格页面
      wx.navigateTo({
        url: '/subcontract/home/pages/goodsSpec/index?goodsId=' + item.goodsId
      });
      return;
    }
    let shopCartList = JSON.parse(wx.getStorageSync('shopCartData'));
    const eventId = app.globalData['btnList.eventId'];
    //只能购买一件产品的时候，对不同对接事件的提示
    if (
      exceedMessageTip({
        eventId,
        shopCartList
      })
    )
      return;
    if (this.timeOut(item.goodsId)) return;
    let spec = this.data.spec;
    (spec.goodsId = item.goodsId), (spec.showSpec = true);
    this.setData({
      spec
    });
  },
  // 通过商品id来获取对应的数组索引，不存在就返回-1,prop是对应的字符串,默认是id
  getIndexById(arr, id, prop = 'id') {
    let tempIndex = -1;
    arr.find((item, index) => {
      if (item[prop] == id) {
        tempIndex = index;
        return true;
      }
    });
    return tempIndex;
  },
  //  通过商品id来获取对应的数组索引数组
  getIndexsById(arr, id, prop = 'id') {
    const res = [];
    arr.forEach((item, index) => {
      if (item[prop] == id) {
        res.push(index);
      }
    });
    return res;
  },
  // 触屏开始滑动
  silderStart(e) {
    const { clientX, clientY, pageX, pageY } = e.changedTouches[0];
    this.setData({
      startClientX: clientX,
      endClientY: clientY,
      startPageX: pageX,
      endPageY: pageY
    });
  },
  // 触屏结束滑动
  async silderEnd(e) {
    if (this.waitGetData) return;
    const {
      startClientX,
      endClientY,
      startPageX,
      endPageY,
      businessList,
      businessId,
      tabIndex,
      businessClassifyList,
      moreData,
      pageNo,
      totalPage
    } = this.data;
    const { clientX, clientY, pageX, pageY } = e.changedTouches[0];
    let tempClientX = clientX - startClientX;
    let tempClientY = clientY - endClientY;
    // let tempPageX = pageX - startPageX
    let tempPageY = pageY - endPageY;
    let index = this.getIndexById(businessList, businessId);
    let length = this.data.businessList.length;
    // 左右滑动
    if (tempClientX < -45 && index + 1 <= length - 1 && Math.abs(tempClientY) < 25) {
      this.businessChange({
        detail: {
          name: businessList[index + 1].id
        }
      });
      // this.getActiveList()
      // this.getBusinessClassifyList()
    }
    if (tempClientX > 45 && index - 1 >= 0 && Math.abs(tempClientY) < 25) {
      this.businessChange({
        detail: {
          name: businessList[index - 1].id
        }
      });
    }
    if (!moreData) return;
    // 判断是否到顶获取到底，只有到顶获取到底了就会请求数据

    if (Math.abs(tempPageY - tempClientY) < 3 && businessClassifyList.length > 0) {
      // setTimeout(async () => {
      if (this.scroll) return;
      // this.scroll = true
      if (tempClientY > 50) {
        if (tabIndex > 0) {
          this.setData({
            tabIndex: tabIndex - 1,
            pageNo: 1,
            upLoading: true
          });
          await this.getListData();
          await this.goodsListScroll();
          this.setData({
            listScrollTop: 0
          });
        }
      } else if (tempClientY < -50 && pageNo == totalPage) {
        if (tabIndex < businessClassifyList.length - 1) {
          this.setData({
            tabIndex: tabIndex + 1,
            pageNo: 1
          });

          await this.getListData();
          await this.goodsListScroll();
          this.setData({
            listScrollTop: 0
          });
        }
      }

      // }, 100)
    }
    // this.scroll = false
  },
  // 直接下单去订单结算页面
  toSubmitOrderPage(e) {
    let item = e.currentTarget.dataset.item;
    if (item) {
      if (this.data.beeperId && item.relationFlag) {
        let spec = this.data.spec;
        spec.goodsId = item.goodsId;
        (spec.showSpec = true),
          this.setData({
            spec
          });
      } else {
        item.nums = 1;
        app.globalData.goodsList = [item];
        wx.navigateTo({
          url: '/subcontract/home/pages/submitOrder/index'
        });
      }
    }
  },
  recordScroll() {
    animation.translateX(70).step();
    this.setData({
      animation: animation.export()
    });
    clearTimeout(this.timer);
    this.timer = setTimeout(() => {
      animation.translateX(0).step();
      this.setData({
        animation: animation.export()
      });
    }, 300);
  },
  // 开始录音
  recordSound() {
    this.selectComponent('#sound-record-two').start();
  },
  // 结束录音
  endSound() {
    this.selectComponent('#sound-record-two').end();
  },
  // 选中日期
  selectDate(e) {
    const { item } = e.target.dataset;
    if (!item) return;
    this.setData({
      dateId: item.id
    });
    app.globalData['dock.date'] = item.date;
    this.getListData();
  },
  // 日期滚动
  dateScroll(e) {
    let { dateScrollInstance } = this.data;
    const { type } = e.currentTarget.dataset;
    dateScrollInstance = type == 2 ? dateScrollInstance + 100 : dateScrollInstance - 100;
    this.setData({
      dateScrollInstance
    });
  },
  dateScrollEnd({ detail: { scrollLeft } }) {
    this.setData({
      dateScrollInstance: scrollLeft
    });
  },
  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {},

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {},

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {},
  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {},
  /**
   * 页面滚动
   */
  onPageScroll: function (e) {
    this.recordScroll();
    const { fixedTop6 } = this.data;
    const flag = e.scrollTop >= fixedTop6 - 10;
    this.setData({
      listScroll: flag ? true : false,
      sideScroll: flag ? true : false
    });
  },
  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {}
});
